package com.task.scheduling.util;

import java.util.concurrent.locks.ReentrantLock;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringContextUtil implements ApplicationContextAware {

	private static ApplicationContext ac;
	private final ReentrantLock lock = new ReentrantLock();
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		try {
			lock.lock();
			SpringContextUtil.ac = applicationContext;
		} finally {
			lock.unlock();
		}
	}

	public static final <T> T getBean(Class<T> clazz) {
		return ac.getBean(clazz);
	}

	public static final <T> T getBean(String name, Class<T> clazz) {
		return ac.getBean(name, clazz);
	}
}